<template>
    <f7-page @page:beforein="pageBeforeIn">
        <f7-navbar>
            <f7-nav-left :back-link="true"></f7-nav-left>
            <f7-nav-title>问题整改</f7-nav-title>
            <f7-nav-right>
                <f7-badge color="blue">已整改</f7-badge>&nbsp;&nbsp;
                <!--<f7-badge color="pink" v-if="timeout">超时</f7-badge>-->
            </f7-nav-right>
        </f7-navbar>
        <f7-list inline-labels no-hairlines no-hairlines-between inset>
            <f7-list-item>
                <f7-label style="width:30%;">标段</f7-label>
                <f7-list-item-cell>
                    {{ $store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].bid_section_name + '(' + $store.state.global.projectMap[$store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].project_id].project_name + ')' }}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">部位</f7-label>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '1' ">
                    {{checkQualityProblem.buildingName + '栋' + checkQualityProblem.unitName + '单元'  + checkQualityProblem.floorName + '层' + checkQualityProblem.roomName}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '2' ">
                    {{checkQualityProblem.buildingName + '栋'  + checkQualityProblem.floorName +'层'}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '3' ">
                    {{checkQualityProblem.buildingName + '栋'}}
                </f7-list-item-cell>
                <f7-list-item-cell v-if="$store.state.global.checkItemGuidelineMap[checkQualityProblem.problemClassId].process_mode == '5' ">
                    {{checkQualityProblem.buildingName + '栋'  + checkQualityProblem.unitName + '单元'  + checkQualityProblem.floorName + '层'}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">检查项</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.problemClassMap[$store.state.global.problemClassMap[checkQualityProblem.problemClassId].parent_problem_class_id].problem_class_name
                    + ' - ' +
                    $store.state.global.problemClassMap[checkQualityProblem.problemClassId].problem_class_name}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
            	<f7-label style="width:30%;">合格率</f7-label>
            	<f7-list-item-cell>
                    <f7-stepper v-if="isRegistUser" fill :value="form.measurePoints" :step="1" :min="0" :max="99"
                                :autorepeat="true" :wraps="true" :manual-input-mode="true"
                                @stepper:change="pointCountChanage">
                    </f7-stepper>
                    <span v-if="!isRegistUser">{{form.measurePoints}}</span>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">合格率</f7-label>
                <f7-list-item-cell>
                    {{form.measurePoints == 0 ? 0 : formatPercent((form.measurePoints - form.problemPoints) / form.measurePoints)}}%
                </f7-list-item-cell>
            </f7-list-item>
			<f7-list-item>
                <f7-label style="width:30%;">爆点数</f7-label>
                <f7-list-item-cell>
                   	{{form.problemPoints}}
                   	<f7-link href="#" v-if="hasDrawingFile && isRegistUser" @click.stop="openHousePointCanEdit">在户型图上标记</f7-link>
                   	<f7-link href="#" v-if="hasDrawingFile && !isRegistUser" @click.stop="openHousePoint">户型图</f7-link>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">检查人</f7-label>
                <f7-list-item-cell>
                    {{$store.state.global.userMap[checkQualityProblem.registBy].realname}}&nbsp;
                    {{problemText(checkQualityProblem.registDate)}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">问题描述</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.remark}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">问题照片</f7-label>
               	<f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(imageFile, i) in checkQualityProblem.imageFile"
                         :src="imageFile.url" @click="$refs.imageFile.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.imageFile"
                                  type="popup" ref="imageFile" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改人</f7-label>
                <f7-list-item-cell>
	                {{$store.state.global.userMap[checkQualityProblem.repairBy].realname}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改照片</f7-label>
                <f7-list-item-cell>
                    <img width="80" height="80" style="margin-right: 5px;"
                         v-for="(repairImageFile, i) in checkQualityProblem.repairImageFile"
                         :src="repairImageFile.url" @click="$refs.repairImageFile.open(i)">
                    </img>
                </f7-list-item-cell>
                <f7-photo-browser :photos="checkQualityProblem.repairImageFile"
                                  type="popup" ref="repairImageFile" back-link-text="关闭">
                </f7-photo-browser>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">整改说明</f7-label>
                <f7-list-item-cell>
                    {{checkQualityProblem.repairRemark}}
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item>
                <f7-label style="width:30%;">抄送人</f7-label>
                <f7-list-item-cell>
	                <span v-for="(user, i) in checkQualityProblem.ccs" style="margin-right:4px;">
	                    {{$store.state.global.userMap[user].realname}}
	                </span>
                </f7-list-item-cell>
            </f7-list-item>
            <f7-list-item v-if="isRegistUser">
                <f7-list-item-cell>
                    <f7-button big round @click="ensureSubmit">通过</f7-button>
                </f7-list-item-cell>
                <f7-list-item-cell>
                    <f7-button big round fill color="red" @click="sendBack">退回</f7-button>
                </f7-list-item-cell>
            </f7-list-item>
        </f7-list>

    </f7-page>
</template>

<script>
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import $ from 'jquery';
import events from 'events';
import store from '@/store';
import request from '@/utils/request';
import { getUser, setUser, clearUser } from '@/utils/auth';

export default {
	store: store,
	props: {
    	checkQualityProblem: {
    		type: Object
    	},
    	sourceIsUnprocessed: {
    		type: Boolean,
    		default: true
    	},
    },
	data: function() {
        return {
            form: {
            	measurePoints: 0,
            	problemPoints: 0,
            	problemValues: [],
            },
        }
    },
	methods: {
		pageBeforeIn: function() {
            this.isOnline = Common.isOnline();
        },
		pointCountChanage: function(value) {
			var self = this;
			var stepper = this.$f7.stepper.get('.stepper');
			if(self.form.problemPoints > value){
				this.$f7.dialog.alert('', '实测点数不能小于爆点数');
				stepper.setValue(self.form.problemPoints);
				return false;
			}else{
				self.form.measurePoints = value;
			}
        },
        formatPercent: function(num) {
            return Math.floor(num * 1000) / 10;
        },
        problemText: function(date) {
            var text = '';
            if(date != null) {
            	text += DateUtil.dateToStr('yyyy-MM-dd HH:mm', date) + ' ';
            }
            return text;
        },
        openHousePoint: function() {
        	var self = this;
            var drawingFile = self.checkQualityProblem.drawingFile[0];
            var router = self.$f7router.navigate('/HousePoint', {
                props: {
                    imageUrl: drawingFile.url,
                    pointCount: self.form.measurePoints,
                    initialPoints: self.form.problemValues,
                    editable: false,
                    hasPointValue: true
                }
            });
    	},
    	openHousePointCanEdit: function() {
    		 var self = this;
             var drawingFile = self.checkQualityProblem.drawingFile[0];
             var router = self.$f7router.navigate('/HousePoint', {
                 props: {
                     imageUrl: drawingFile.url,
                     pointCount: self.form.measurePoints,
                     initialPoints: self.form.problemValues,
                     editable: true,
                     overPointCountMessage: '爆点数不能超过测量点数',
                     hasPointValue: true
                 }
             });
             router.off('pointAdd');
             router.on('pointAdd', function(point) {
                 self.form.problemValues.push(point);
                 self.form.problemPoints++;
             });
             router.off('pointDelete');
             router.on('pointDelete', function(point) {
                 for(var i = 0; i < self.form.problemValues.length; i++) {
                     if(point.x == self.form.problemValues[i].x
                         && point.y == self.form.problemValues[i].y) {
                         self.form.problemValues.splice(i, 1);
                         self.form.problemPoints--;
                         break;
                     }
                 }
             });
             router.off('pointChange');
             router.on('pointChange', function(point) {
                 for(var i = 0; i < self.form.problemValues.length; i++) {
                     if(point.x == self.form.problemValues[i].x
                         && point.y == self.form.problemValues[i].y) {
                         self.form.problemValues.splice(i, 1, point);
                         break;
                     }
                 }
             });
    	},
    	sendBack: function() {
        	var self = this;
        	let sql = "\
    	        select * from offline_quality_measure_sendBack \
    	        where problem_id = '" + self.checkQualityProblem.qualityMeasureCheckqualityProblemId + "' \
    	    ";
			Common.executeSql(sql, []).then((result) => {
				let rs = result.rs;
				let problemSendBack = {
					photos: []
				};
				if(rs.rows.length != 0) {
					let row = rs.rows.item(0);
	    			let photo = Common.strToJson(row.offline_sendBack_image_file);
	    			problemSendBack.photos.push(photo);
	    			problemSendBack.tid = row.tid;
	    			problemSendBack.remark = row.offline_sendBack_remark;
	    			problemSendBack.backReasonValue = row.back_reason_value;
				}
				var router = null;
				if(self.sourceIsUnprocessed) {
		       		router = this.$f7router.navigate('/SendBack', {
						props: {
							problemId: self.checkQualityProblem.qualityMeasureCheckqualityProblemId,
							module: 'qualityMeasure',
							submitUrl: '/rest/api/v3/qualityMeasureCheckQualityProblem/problemSendBack',
							backUrl: '/UnprocessedQualityMeasureMain/',
							updateable: true,
							updateProblemApi: 'problemStautsChange',
							problemSendBack: problemSendBack
						}
					});
	        	} else {
	        		var backUrl = self.$f7router.history[self.$f7router.history.length-2];
	        		router = this.$f7router.navigate('/SendBack', {
						props: {
							problemId: self.checkQualityProblem.qualityMeasureCheckqualityProblemId,
							module: 'qualityMeasure',
							submitUrl: '/rest/api/v3/qualityMeasureCheckQualityProblem/problemSendBack',
							updateable: true,
							updateProblemApi: 'problemSendBackFinish',
							problemSendBack: problemSendBack
						}	
					});
	        		router.off('problemSendBackFinish');
	                router.on('problemSendBackFinish', function(qualityMeasureProblem) {
	                	self.$emit('problemUpdate', qualityMeasureProblem);
	                    self.$f7router.emit('problemUpdate', qualityMeasureProblem);
	                });
	                
	        	}
				router.off('saveTemporaryProblemSendBack');
                router.on('saveTemporaryProblemSendBack', function(form) {
                	let sql = "";
            		if(form.tid == null) {
                        sql = "\
                            insert into offline_quality_measure_sendBack( \
                            problem_id, offline_sendBack_image_file, \
                            offline_sendBack_remark, \
                            back_reason_value) \
                            values (?, ?, ?, ?) \
                        ";  
                    } else {
                        sql = "\
                            update offline_quality_measure_sendBack \
                            set problem_id = ?, offline_sendBack_image_file = ?, \
                            offline_sendBack_remark = ?, \
            	            back_reason_value = ? \
                            where tid = '" + form.tid + "' \
                        ";
                    }
            		let values = [
            			form.problemId,
            			JSON.stringify(form.photos),
            			form.remark,
            			form.backReasonValue
            		];
            		Common.executeSql(sql, values).then((result) => {
            			self.$f7.dialog.alert('', '暂存问题成功！');
            		}).catch(error => {
            			console.error(error);
            			self.$f7.dialog.alert('', '暂存问题失败！');
            		});
                });
			}).catch(error => {
				console.error(error);
			});
        },
        ensureSubmit: function(){
            var self = this;
            this.$f7.dialog.confirm("您确定通过？","",function () {
                self.submit();
            });
        },
        submit: function() {
        	var self = this;
        	self.$f7.preloader.show();
            var data = {
            	qualityMeasureCheckQualityProblemId: self.checkQualityProblem.qualityMeasureCheckqualityProblemId,
            	registUserId: getUser().userId,
            	measurePoints: self.form.measurePoints,
            	points: []
            };
            self.form.problemValues.forEach(function(problemValue) {
            	let point = {};
                point.value = problemValue.val;
                if(problemValue.x != null){
                	point.x = problemValue.x;
                }
                if(problemValue.x != null){
                	point.y = problemValue.y;
                }
                data.points.push(point);
            });
            request({
        		url: '/rest/api/v3/qualityMeasureCheckQualityProblem/problemRepairCompleted',
                method: 'POST',
                data: data
            }).then((result) => {
            	self.$f7.dialog.alert(result.msg, '问题通过成功！');
                self.$f7router.back();
                if(self.sourceIsUnprocessed) {
                	self.$emit('problemStautsChange', result.element);
                    self.$f7router.emit('problemStautsChange', result.element);
                } else {
                	self.$emit('problemUpdate', result.element);
                    self.$f7router.emit('problemUpdate', result.element);
                }
                
                self.$f7.preloader.hide();
            }).catch(error => {
    			console.error(error);
    			self.$f7.dialog.alert('', '问题通过失败！');
        		self.$f7.preloader.hide();
    		});
            
        },
    },
	computed: {
		hasDrawingFile: function() {
            var drawingFile = this.checkQualityProblem.drawingFile;
            if(drawingFile == null || drawingFile.length == 0) {
                return false;
            } else {
                return true;
            }
        },
        isRegistUser: function() {
        	var currentUserId = getUser().userId;
            if(this.checkQualityProblem.registBy == currentUserId) {
                return true;
            }
            return false;
        },
    },
    created: function() {
        
    },
    watch: {
        
    },
    mounted: function () {
        var self = this;
        self.form.measurePoints = self.checkQualityProblem.measurePoints;
        self.form.problemPoints = self.checkQualityProblem.problemPoints;
        self.form.problemValues = self.checkQualityProblem.problemValues;
    }
}
</script>

<style scoped>

</style>